<template>
  <el-container class="layout-container">
    <!-- 侧边栏 -->
    <el-aside width="250px" class="sidebar">
      <div class="logo">
        <h2>学生管理系统</h2>
      </div>
      <el-menu
        :default-active="$route.path"
        class="sidebar-menu"
        background-color="#304156"
        text-color="#bfcbd9"
        active-text-color="#409EFF"
        router
      >
        <el-menu-item v-if="role === 'admin'" index="/dashboard/home">
          <el-icon><House /></el-icon>
          <span>首页</span>
        </el-menu-item>
        <el-menu-item v-if="role === 'student'" index="/dashboard/student">
          <el-icon><User /></el-icon>
          <span>我的信息</span>
        </el-menu-item>
        <el-menu-item v-if="role === 'teacher'" index="/dashboard/teacher">
          <el-icon><Avatar /></el-icon>
          <span>我的信息</span>
        </el-menu-item>
        <el-menu-item v-if="role === 'teacher'" index="/dashboard/teacher-score">
          <el-icon><Tickets /></el-icon>
          <span>成绩管理</span>
        </el-menu-item>
        <el-menu-item v-if="role === 'admin'" index="/dashboard/student">
          <el-icon><User /></el-icon>
          <span>学生管理</span>
        </el-menu-item>
        <el-menu-item v-if="role === 'admin'" index="/dashboard/teacher">
          <el-icon><Avatar /></el-icon>
          <span>教师管理</span>
        </el-menu-item>
        <el-menu-item v-if="role === 'student'" index="/dashboard/score">
          <el-icon><Tickets /></el-icon>
          <span>我的成绩</span>
        </el-menu-item>
        <el-menu-item v-if="role === 'admin'" index="/dashboard/users">
          <el-icon><Setting /></el-icon>
          <span>用户权限管理</span>
        </el-menu-item>
      </el-menu>
    </el-aside>

    <!-- 主内容区 -->
    <el-container>
      <el-header class="header">
        <div class="header-content">
          <h3>{{ currentTitle }}</h3>
          <div class="user-info">
            <el-dropdown>
              <span class="user-dropdown">
                {{ username }} <el-icon><ArrowDown /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleDeleteAccount" style="color: #f56c6c">注销账号</el-dropdown-item>
                  <el-dropdown-item divided @click="handleLogout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </el-header>
      <el-main class="main-content">
        <router-view />
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import { computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { House, User, Avatar, Tickets, Setting, ArrowDown } from '@element-plus/icons-vue'
import loginAPI from '../api/login'

export default {
  name: 'Layout',
  setup() {
    const route = useRoute()
    const router = useRouter()
    
    const currentTitle = computed(() => {
      return route.meta.title || '首页'
    })
    
    const username = computed(() => {
      return localStorage.getItem('username') || '管理员'
    })
    
    const role = computed(() => localStorage.getItem('role') || 'student')
    
    const handleLogout = async () => {
      try {
        await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        // 调用后端退出接口
        try {
          await loginAPI.logout(username.value)
        } catch (error) {
          console.warn('后端退出接口调用失败:', error)
          // 即使后端调用失败，也要清除本地存储
        }
        
        // 清除本地存储
        localStorage.removeItem('isLoggedIn')
        localStorage.removeItem('username')
        localStorage.removeItem('role')
        localStorage.removeItem('userId')
        
        ElMessage.success('退出登录成功')
        router.push('/login')
      } catch (error) {
        // 用户取消操作
      }
    }
    
    // 处理账号注销
    const handleDeleteAccount = async () => {
      try {
        // 第一次确认
        await ElMessageBox.confirm(
          '警告：注销账号将永久删除您的所有数据，且无法恢复！\n\n确定要继续吗？',
          '危险操作',
          {
            confirmButtonText: '继续',
            cancelButtonText: '取消',
            type: 'error',
            dangerouslyUseHTMLString: true
          }
        )
        
        // 第二次确认
        await ElMessageBox.confirm(
          '请再次确认：您真的要注销账号吗？这个操作不可逆转！',
          '最后确认',
          {
            confirmButtonText: '我确定要注销',
            cancelButtonText: '取消',
            type: 'error'
          }
        )
        
        // 第三次确认（输入确认文本）
        const { value } = await ElMessageBox.prompt(
          '请输入 "我要注销账号" 来确认操作：',
          '输入确认',
          {
            confirmButtonText: '确定注销',
            cancelButtonText: '取消',
            inputPattern: /^我要注销账号$/,
            inputErrorMessage: '请输入“我要注销账号”',
            inputPlaceholder: '请输入：我要注销账号'
          }
        )
        
        if (value !== '我要注销账号') {
          ElMessage.error('确认文本不正确，操作取消')
          return
        }
        
        const userId = localStorage.getItem('userId')
        if (!userId) {
          ElMessage.error('获取用户ID失败')
          return
        }
        
        // 调用注销接口
        await loginAPI.deleteUser(userId)
        
        // 清除本地存储
        localStorage.removeItem('isLoggedIn')
        localStorage.removeItem('username')
        localStorage.removeItem('role')
        localStorage.removeItem('userId')
        
        ElMessage.success('账号注销成功')
        router.push('/login')
        
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('账号注销失败：' + (error.message || '未知错误'))
        }
      }
    }
    
    return {
      currentTitle,
      username,
      handleLogout,
      handleDeleteAccount,
      role,
      House,
      User,
      Avatar,
      Tickets,
      Setting,
      ArrowDown
    }
  }
}
</script>

<style scoped>
.layout-container {
  height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.sidebar {
  background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
  color: white;
  box-shadow: 4px 0 15px rgba(0,0,0,0.1);
  position: relative;
  z-index: 1000;
}

.sidebar::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="dots" width="20" height="20" patternUnits="userSpaceOnUse"><circle cx="10" cy="10" r="1" fill="%23ffffff" opacity="0.02"/></pattern></defs><rect width="100" height="100" fill="url(%23dots)"/></svg>');
  pointer-events: none;
}

.logo {
  height: 70px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #1a252f 0%, #2c3e50 100%);
  color: white;
  position: relative;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.logo h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 700;
  background: linear-gradient(45deg, #74b9ff, #00cec9);
  background-clip: text;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  text-shadow: 0 2px 4px rgba(0,0,0,0.3);
}

.sidebar-menu {
  border-right: none;
  background: transparent;
  padding: 12px 0;
}

.sidebar-menu .el-menu-item {
  position: relative;
  margin: 6px 12px;
  border-radius: 12px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  color: rgba(255,255,255,0.8);
  font-weight: 500;
  padding-left: 20px;
}

.sidebar-menu .el-menu-item:hover {
  background: linear-gradient(135deg, rgba(116, 185, 255, 0.15) 0%, rgba(0, 206, 201, 0.15) 100%);
  color: #74b9ff;
  transform: translateX(4px);
  box-shadow: 0 4px 12px rgba(116, 185, 255, 0.2);
}

.sidebar-menu .el-menu-item.is-active {
  background: linear-gradient(135deg, #74b9ff 0%, #00cec9 100%);
  color: white;
  box-shadow: 0 6px 20px rgba(116, 185, 255, 0.4);
  transform: translateX(6px);
}

.sidebar-menu .el-menu-item.is-active::before {
  content: '';
  position: absolute;
  left: -12px;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 30px;
  background: linear-gradient(to bottom, #74b9ff, #00cec9);
  border-radius: 2px;
  box-shadow: 0 0 10px rgba(116, 185, 255, 0.6);
}

.sidebar-menu .el-menu-item .el-icon {
  margin-right: 12px;
  font-size: 18px;
  transition: all 0.3s ease;
}

.sidebar-menu .el-menu-item:hover .el-icon,
.sidebar-menu .el-menu-item.is-active .el-icon {
  transform: scale(1.1);
}

.header {
  background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
  border-bottom: 1px solid rgba(0,0,0,0.06);
  padding: 0 30px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
  backdrop-filter: blur(10px);
  position: relative;
}

.header::before {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(90deg, #74b9ff 0%, #00cec9 50%, #fd79a8 100%);
  opacity: 0.8;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.header-content h3 {
  margin: 0;
  color: #2d3748;
  font-size: 22px;
  font-weight: 700;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  background-clip: text;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.user-info {
  position: relative;
}

.user-dropdown {
  cursor: pointer;
  color: #4a5568;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 16px;
  border-radius: 12px;
  background: linear-gradient(135deg, #f7fafc 0%, #edf2f7 100%);
  border: 1px solid rgba(0,0,0,0.05);
  transition: all 0.3s ease;
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}

.user-dropdown:hover {
  background: linear-gradient(135deg, #ebf8ff 0%, #bee3f8 100%);
  color: #2b6cb0;
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(116, 185, 255, 0.2);
}

.main-content {
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  padding: 30px;
  min-height: calc(100vh - 120px);
  position: relative;
  overflow-x: hidden;
}

.main-content::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="pattern" width="20" height="20" patternUnits="userSpaceOnUse"><circle cx="10" cy="10" r="0.5" fill="%2374b9ff" opacity="0.02"/></pattern></defs><rect width="100" height="100" fill="url(%23pattern)"/></svg>');
  pointer-events: none;
  z-index: 0;
}

.main-content > * {
  position: relative;
  z-index: 1;
}

/* 添加响应式设计 */
@media (max-width: 768px) {
  .layout-container {
    flex-direction: column;
  }
  
  .sidebar {
    width: 100% !important;
    height: auto;
  }
  
  .header {
    padding: 0 15px;
  }
  
  .header-content h3 {
    font-size: 18px;
  }
  
  .main-content {
    padding: 20px 15px;
  }
}
</style>
